package xml;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class EmailParser {
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		File f = new File("/home/tarena/0hean/hean/src/xml/email.xml");
		Email email=parse(f);
		System.out.println(email);
		for (Iterator it = email.getTo().iterator(); it.hasNext();) {
			To to = (To) it.next();
			System.out.println(to);
		}
	}

	private static Email parse(File f) throws ParserConfigurationException,
			SAXException, IOException {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		EmailHandler emailHandler = new EmailHandler();
		parser.parse(f, emailHandler);
		Email email = emailHandler.getEmail();
		return email;
	}

	static class EmailHandler extends DefaultHandler {
		String xpath="";
		Email email = new Email();
		To to;
		public EmailHandler() {
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			xpath+="/"+qName;
			System.out.println(xpath);
			if("/email".equals(xpath)){
				email.setDate(attributes.getValue("date"));
				email.setEmotion(attributes.getValue("emotion"));
				email.setThinking(attributes.getValue("thinking"));
			}else if("/email/to".equals(xpath)){
				to = new To();
				email.to.add(to);
			}
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			String s = new String(ch,start,length);
			if("/email/from".equals(xpath)){
				email.setFrom(s);
			}else if("/email/subject".equals(xpath)){
				email.setSubject(s);
			}else if ("/email/body".equals(xpath)) {
				email.setBody(s);
			}else if ("/email/to/to-email".equals(xpath)) {
				to.setToemail(s);
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			xpath = xpath.substring(0,xpath.lastIndexOf("/"));
			System.out.println(xpath);
			
		}

		public Email getEmail() {
			return email;
		}

	}
}
